#include <assert.h>
#include <config.h>
#include <material/textureeditor/textureeditordialog.h>
#include <session.h>
#include <qevent.h>
#include <qfileinfo.h>
#include <qmessagebox.h>
#include <qmimedata.h>
#include <material/materialmanager.h>
#include <stdio.h>


cceMaterialTextureView::cceMaterialTextureView (QWidget *parent)
	: QGraphicsView (parent)
{
	setAcceptDrops(true);
	setDragMode(QGraphicsView::ScrollHandDrag);
}

namespace
{
bool test_drag (const QMimeData *md)
{
	if (md->hasFormat (CCE_FILESYSTEM_MIME))
		{
			QString name = md->data(CCE_FILESYSTEM_MIME);

			QFileInfo info (name);
			QString ext = info.suffix().toLower().trimmed();
			if (ext == "jpg" || ext == "jpeg" ||
					ext == "png" || ext == "tga" ||
					ext == "bmp")
				{
					return true;
				}
		}
	return false;
}
}

void cceMaterialTextureView::dragEnterEvent(QDragEnterEvent *event)
{
	if (test_drag(event->mimeData()))
		{
			event->accept();
		}
}

void cceMaterialTextureView::dragMoveEvent(QDragMoveEvent *event)
{
	if (test_drag (event->mimeData()))
		{
			event->accept();
		}
}

void cceMaterialTextureView::dropEvent(QDropEvent *event)
{
	const QMimeData* md = event->mimeData();

	if (md->hasFormat (CCE_FILESYSTEM_MIME))
		{
			QString name = md->data(CCE_FILESYSTEM_MIME);
			QFileInfo info (name);
			QString ext = info.suffix().toLower().trimmed();
			if (ext == "jpg" || ext == "jpeg" ||
					ext == "png" || ext == "tga" ||
					ext == "bmp")
				{
					emit TextureChanged(name);
				}
		}
}



cceMaterialTextureEditorDialog::cceMaterialTextureEditorDialog(QWidget *parent)
  : cceMaterialEditorAbstract (parent)
  , _texture (0)
{
  _gui.setupUi(this);

	_view = new cceMaterialTextureView (_gui.widgetView);
	QGridLayout *layout = new QGridLayout(_gui.widgetView);
	layout->addWidget(_view);

  _scene = new QGraphicsScene (this);
	_view->setScene(_scene);

	_pixmap = new QGraphicsPixmapItem();
	_pixmap->setAcceptDrops(false);
	_scene->addItem(_pixmap);
	connect (_view, SIGNAL(TextureChanged(const QString&)), this, SLOT(ChangeTexture (const QString&)));
}


cceMaterialTextureEditorDialog::~cceMaterialTextureEditorDialog()
{

}

void cceMaterialTextureEditorDialog::SetTexture(cceMaterialTexture *texture)
{
  _texture = texture;
	connect (_texture, SIGNAL(Removed()), this, SLOT(ForceClose()));
  UpdateGUIFromTexture ();
}

void cceMaterialTextureEditorDialog::ForceClose()
{
	emit CloseEditor(_texture);
}

QString cceMaterialTextureEditorDialog::GetName() const
{
	if (_texture)
		{
			return _texture->GetName();
		}
	return "";
}

bool cceMaterialTextureEditorDialog::Save()
{
  return UpdateTextureFromGUI();
}

void cceMaterialTextureEditorDialog::UpdateGUIFromTexture()
{
	assert (_texture);
	_gui.lineEditName->setText(GetEditorName(_texture->GetName()));
  _gui.comboBoxWrapMode->setCurrentIndex(_texture->GetWrap());

  int idx = _gui.comboBoxTextureGroup->findText(_texture->GetGroup());
  if (idx >= 0)
    {
      _gui.comboBoxTextureGroup->setCurrentIndex(idx);
    }
  else
    {
      _gui.comboBoxTextureGroup->addItem (_texture->GetGroup());
      _gui.comboBoxTextureGroup->setEditText(_texture->GetGroup());
    }

	SetImage (_texture->GetFilename());
}

bool cceMaterialTextureEditorDialog::UpdateTextureFromGUI()
{
	assert (_texture);
	cceMaterialTexture* txt = _manager->GetTexture(_gui.lineEditName->text() + ".tex");
	if (txt && txt != _texture)
		{
			QMessageBox::information(this,
															 "Texture - " CCE_TOOL_NAME,
															 "The texture name is already in use.\nPlease enter a unique texture name.");
			return false;
		}

	_texture->SetName(_gui.lineEditName->text() + ".tex");
	_texture->SetFilename(_filename);
  _texture->SetGroup(_gui.comboBoxTextureGroup->currentText());
  _texture->SetWrap((cceMaterialTexture::Wrap)_gui.comboBoxWrapMode->currentIndex());
	_texture->Change();

	if (_texture->IsNew() && _manager)
		{
			_manager->AddTexture(_texture);
		}


  SetChanged(false);
	return true;
}

void cceMaterialTextureEditorDialog::on_comboBoxTextureGroup_editTextChanged(const QString &)
{
  SetChanged(TextureChanged());
}

void cceMaterialTextureEditorDialog::on_comboBoxWrapMode_currentIndexChanged(int)
{
  SetChanged(TextureChanged());
}

void cceMaterialTextureEditorDialog::on_lineEditName_textChanged(const QString &)
{
  SetChanged(TextureChanged());
}


void cceMaterialTextureEditorDialog::Close()
{
	if (TextureChanged ())
		{
			int result = QMessageBox::question (this,
				"Texture changed - " CCE_TOOL_NAME,
				"The texture has unsaved changes. Save changes bevor closing?",
				QMessageBox::Save, QMessageBox::Close, QMessageBox::Cancel);
			switch (result)
				{
				case QMessageBox::Save:
					Save ();
					break;

				case QMessageBox::Cancel:
					return;

				case QMessageBox::Close:
					break;
				}
		}
	emit CloseEditor(_texture);
}

bool cceMaterialTextureEditorDialog::TextureChanged()
{
  if (!_texture)
    {
      return false;
    }
	if (GetEditorName(_texture->GetName()) != _gui.lineEditName->text()) return true;
	if (_texture->GetFilename() != _filename) return true;
  if (_texture->GetGroup() != _gui.comboBoxTextureGroup->currentText()) return true;
  if (_texture->GetWrap() != _gui.comboBoxWrapMode->currentIndex()) return true;

	// test the texture wrap
	return false;
}


void cceMaterialTextureEditorDialog::ChangeTexture(const QString &filename)
{
	QString name = cceSession::Get()->GetMaterialManager()->CopyTextureFilename(filename);
	if (name.isNull())
		{
			_pixmap->setPixmap(QPixmap ());
			return;
		}

	SetImage(name);
  SetChanged(TextureChanged());
}

void cceMaterialTextureEditorDialog::SetImage(const QString &image)
{
	_filename = image;
	const QString& filename = cceSession::Get()->GetFileName("/" CCE_MATERIAL_TEXTURES_FOLDER "/"+image);
	QImage img;
	if (img.load(filename))
		{
			QPixmap pm = QPixmap::fromImage(img);
			_pixmap->setPixmap(pm);
		}

}

